package cn.gok.common.config;

import cn.gok.common.entity.backstage.SysUser;
import cn.gok.server.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @auther: shikundai
 * @Time: 2020/9/24  18:03
 * @description:
 */
@Component
public class UserRealm extends AuthorizingRealm {

    @Resource(name = "sysUserServiceImpl")
    private SysUserService sysUserService;

    /**
     * 用户授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        long id = ((SysUser) SecurityUtils.getSubject().getPrincipal()).getUserId();
        //查询用户角色名
        simpleAuthorizationInfo.addRole(sysUserService.getRoleById(id));
        //查询用户权限字串
        simpleAuthorizationInfo.addStringPermissions(sysUserService.getPermissionsById(id));
        return simpleAuthorizationInfo;
    }

    /**
     * 用户认证
     *
     * @param authenticationToken
     * @return SimpleAuthenticationInfo
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;

        String username = usernamePasswordToken.getPrincipal().toString();
        if (username != null) {
            SysUser sysUser = sysUserService.login(username);
            if (sysUser != null) {
                return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), null, getName());
            }
        }
        return new SimpleAuthenticationInfo(username, null, getName());
    }
}
